package com.enterprise.support.utility;


import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static java.net.URLEncoder.encode;


/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:36
 * Email: z82422@gmail.com
 * 用户 操作辅助对象
 */
public class UserUtility {
    private static Logger logger = Logger.getLogger(UserUtility.class);
    public static String WEB_SESSION_USER_KEY = "web_session_user_key";
    public static String WEB_SESSION_ADMIN_KEY = "web_session_admin_key";

    public static Enterprise onlineUserEntitys = new Enterprise();

    /**
     * 检测用户是否在线
     *
     * @param user
     * @return
     */
    public static boolean isOnlineUser(Enterprise user) {
        return onlineUserEntitys.containsKey(user.getIntId());
    }

    /**
     * 获取在线用户数量
     *
     * @return
     */
    public static Integer getOnlineUserCount() {
        return onlineUserEntitys.size();
    }

    /**
     * 获取在线用户列表
     *
     * @return
     */
    public static List<Enterprise> getOnlineUserList() {
        return new ArrayList(onlineUserEntitys.values());
    }

    /**
     * 检测用户是否 登录
     *
     * @param request
     * @return
     */
    public static boolean isLoginUser(HttpServletRequest request) {
        return Validation.isNotEmpty(getUserInfo(request));
    }

    public static boolean isLoginUser() {
        return isLoginUser(ActionContext.getContext().getRequest());
    }

    /**
     * 检测管理员是否 登录
     *
     * @param request
     * @return
     */
    public static boolean isLoginAdmin(HttpServletRequest request) {
        return Validation.isNotEmpty(getAdminInfo(request)) && !getAdminInfo(request).isEmpty("username");
    }

    public static boolean isLoginAdmin() {
        return isLoginAdmin(ActionContext.getContext().getRequest());
    }

    /**
     * 设置用户登录
     *
     * @param request
     * @param enterprise
     */
    public static void setLoginUser(HttpServletRequest request, Enterprise enterprise) {
        if (!Configuration.get().getBoolean("web_info_in_cookie")) {
            if (Validation.isNotEmpty(request) && Validation.isNotEmpty(request.getSession(true))) {
                request.getSession(true).setAttribute(WEB_SESSION_USER_KEY, enterprise);
            }
        } else {
            HttpServletResponse response = ActionContext.getContext().getResponse();
            for (String key : (Set<String>) enterprise.keySet()) {
                try {
                    Cookie cookie = new Cookie(WEB_SESSION_USER_KEY + key, encode(enterprise.isEmpty(key) ? "" : enterprise.getString(key), "utf-8"));
                    cookie.setMaxAge(Configuration.get().getInt("web_info_in_cookie.timeout"));
                    cookie.setPath(Configuration.get().getString("web_info_in_cookie.path"));
                    response.addCookie(cookie);
                } catch (Exception ex) {
                    logger.error("写入Cookie异常,key=" + key + ",完整参数:" + enterprise, ex);
                }
            }
        }
    }

    public static void setLoginUser(Enterprise enterprise) {
        setLoginUser(ActionContext.getContext().getRequest(), enterprise);
    }

    /**
     * 设置用户登录
     *
     * @param request
     * @param enterprise
     */
    public static void setLoginAdmin(HttpServletRequest request, Enterprise enterprise) {
        if (!Configuration.get().getBoolean("web_info_in_cookie")) {
            if (Validation.isNotEmpty(request) && Validation.isNotEmpty(request.getSession(true))) {
                request.getSession(true).setAttribute(WEB_SESSION_ADMIN_KEY, enterprise);
            }
        } else {
            HttpServletResponse response = ActionContext.getContext().getResponse();
            for (String key : (Set<String>) enterprise.keySet()) {
                try {
                    Cookie cookie = new Cookie(WEB_SESSION_ADMIN_KEY + key, encode(enterprise.isEmpty(key) ? "" : enterprise.getString(key), "utf-8"));
                    cookie.setMaxAge(Configuration.get().getInt("web_info_in_cookie.timeout"));
                    cookie.setPath(Configuration.get().getString("web_info_in_cookie.path"));
                    response.addCookie(cookie);
                } catch (Exception ex) {
                    logger.error("写入Cookie异常,key=" + key + ",完整参数:" + enterprise, ex);
                }
            }
        }
    }

    public static void setLoginAdmin(Enterprise info) {
        setLoginAdmin(ActionContext.getContext().getRequest(), info);
    }

    /**
     * 获取当前登录用户对象
     *
     * @param request
     * @return
     */
    public static Enterprise getUserInfo(HttpServletRequest request) {
        if (!Configuration.get().getBoolean("web_info_in_cookie")) {
            return (Validation.isEmpty(request) || Validation.isEmpty(request.getSession())) ? null : (Enterprise) request.getSession().getAttribute(WEB_SESSION_USER_KEY);
        } else {
            Enterprise cookie = WebUtility.getCookies();
            Enterprise cookieTemp = new Enterprise();
            for (String key : (Set<String>) cookie.keySet()) {
                if (key.startsWith(WEB_SESSION_USER_KEY)) {
                    cookieTemp.put(key.replace(WEB_SESSION_USER_KEY, ""), cookie.getString(key));
                }
            }
            if (cookieTemp.size() < 1 || cookieTemp.isEmpty("username")) {
                return null;
            }
            return cookieTemp;
        }
    }

    public static Enterprise getUserInfo() {
        return getUserInfo(ActionContext.getContext().getRequest());
    }

    public static <T extends Enterprise> T getUserInfo(Class<T> params) {
        return (T) getUserInfo(ActionContext.getContext().getRequest());
    }

    /**
     * 获取当前登录管理员对象
     *
     * @param request
     * @return
     */
    public static Enterprise getAdminInfo(HttpServletRequest request) {
        if (!Configuration.get().getBoolean("web_info_in_cookie")) {
            return (Validation.isEmpty(request) || Validation.isEmpty(request.getSession())) ? null : (Enterprise) request.getSession().getAttribute(WEB_SESSION_ADMIN_KEY);
        } else {
            Enterprise cookie = WebUtility.getCookies();
            Enterprise cookieTemp = new Enterprise();
            for (String key : (Set<String>) cookie.keySet()) {
                if (key.startsWith(WEB_SESSION_ADMIN_KEY)) {
                    cookieTemp.put(key.replace(WEB_SESSION_ADMIN_KEY, ""), cookie.getString(key));
                }
            }
            if (cookieTemp.size() < 1 || cookieTemp.isEmpty("username")) {
                return null;
            }
            return cookieTemp;
        }
    }

    public static Enterprise getAdminInfo() {
        return getAdminInfo(ActionContext.getContext().getRequest());
    }

    public static <T extends Enterprise> T getAdminInfo(Class<T> params) {
        return (T) getAdminInfo(ActionContext.getContext().getRequest());
    }
}
